﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Xml;
using TimeMachine.Engine.Metrics;

namespace TimeMachine.Engine.Storing.Impl
{
	public class XmlMetricsSaver : IMetricsSaver
	{
		private readonly IMetricValuesStorageDisposition metricsStorageDisposition;

		public XmlMetricsSaver(IMetricValuesStorageDisposition metricsStorageDisposition)
		{
			this.metricsStorageDisposition = metricsStorageDisposition;
		}

		public void WriteMetrics(string metricId, IEnumerable<MetricValue> commits)
		{
			var settings = new XmlWriterSettings {Indent = true, CloseOutput = true};
			using (XmlWriter writer = XmlWriter.Create(metricsStorageDisposition.GetMetricsFilename(metricId), settings))
			{
				if (writer == null) throw new Exception("writer == null");
				writer.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
				writer.WriteStartElement("metric-values");
				writer.WriteAttributeString("id", metricId);
				foreach(var commit in commits)
				{
					writer.WriteStartElement("commit");
					writer.WriteAttributeString("rev", commit.Rev.ToString());
					writer.WriteAttributeString("value", commit.Value.ToString(NumberFormatInfo.InvariantInfo));
					writer.WriteEndElement();
				}
				writer.WriteEndElement();
			}
		}
	}
}